//
// Created by none98 on 2021/9/10.
//

#ifndef LOGINSERVER_TCPSERVER_H
#define LOGINSERVER_TCPSERVER_H


#include <memory>
#include <map>
#include "CallBacks.h"
#include "TcpConnection.h"


#include <mutex>

class EventLoop;
class TcpConnection;
class Acceptor;

class TcpServer {
public:
    TcpServer();
    ~TcpServer();

    inline void OnMessage(const MessageCallBack &msgCallBack){
        this->msgCallBack=msgCallBack;
    }

    inline void OnClose(const TcpCallBack &callBack){
        closeCallBack = callBack;
    }

    inline void OnConnection(const TcpCallBack &callBack){
        connectionCallBack = callBack;
    }

    inline void OnWriteComplete(const TcpCallBack &callBack){
        writeCompleteCallBack = callBack;
    }

    inline void SetKeepAlive(bool option){
        keepAlive = option;
    }

    int GetConnectionSize();

    long AddTimer(int hours,int minutes, int seconds, int milliSeconds, const TimerCallBack &callBack,bool isCycle)const;

    void Start(const std::string &address, int port);



private:
    void RegisterConnection(TcpConnectionPtr connection);

    void CloseConnection(TcpConnectionPtr connection);


    bool keepAlive;

    std::unique_ptr<EventLoop> loop;
    std::unique_ptr<Acceptor> acceptor;

    MessageCallBack msgCallBack;
    TcpCallBack connectionCallBack;
    TcpCallBack closeCallBack;
    TcpCallBack writeCompleteCallBack;

    //manage conns and control its life
    std::mutex mapMutex;
    std::map<int,std::shared_ptr<TcpConnection>> connectionMap;
};



#endif //LOGINSERVER_TCPSERVER_H
